
"""
    udp聊天器
        1、发送消息  （默认给本机发送）
        2、接收消息  （默认接收本机发送的消息）
        3、退出系统
"""
import socket


def send_mes():
    print("输入发送的ip：")
    send_ip = input()
    if send_ip == "":
        send_ip = "127.0.0.1"
        print("使用默认ip127.0.0.1")
    print("输入目标端口：")
    send_port = input()
    if send_port == "":
        send_port = 8080
        print("默认向目标8080端口发送")
    send_port = int(send_port)
    print("输入要发送的信息：")
    send_info = input()
    udp_so = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

    udp_so.sendto(send_info.encode(), (send_ip, send_port))
    udp_so.close()
    show_menu()


def recv_mes():
    udp_so = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

    # 默认udp接收端口8081
    addr = ("127.0.0.1", 8081)
    udp_so.bind(addr)
    print("请向127.0.0.1:8081发送消息")
    recv_info, _ = udp_so.recvfrom(1024)
    recv_data = recv_info.decode("GBK")
    print("收到消息：", recv_data)
    udp_so.close()
    show_menu()


def show_menu():
    print("输入序号选择功能：")
    print("*" * 23)
    print("*"*5, "1、发送消息", "*"*5)
    print("*"*5, "2、接收消息", "*"*5)
    print("*"*5, "3、退出系统", "*"*5)
    print("*" * 23)


def select_func():
    show_menu()
    while True:
        in_str = input()
        try:
            in_mes = int(in_str)
            if in_mes <= 0 or in_mes > 3:
                print("输入正确数字")
            elif in_mes == 1:
                send_mes()
            elif in_mes == 2:
                recv_mes()
            elif in_mes == 3:
                break
        except Exception as e:
            print("请输入数字")


if __name__ == '__main__':
    select_func()
